package cn.qayy.controller;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.qayy.constants.CollectionConstant;
import cn.qayy.constants.Constant;
import cn.qayy.dto.ClientBankDTO;
import cn.qayy.dto.Msg;
import cn.qayy.dto.MsgInfo;
import cn.qayy.dto.PolicyAllDTO;
import cn.qayy.dto.PolicyDTO;
import cn.qayy.dto.PolicyDTO_RE;
import cn.qayy.dto.PolicyDemoWCL;
import cn.qayy.dto.QueryVO;
import cn.qayy.po.Bid;
import cn.qayy.po.Plan;
import cn.qayy.po.Policy;
import cn.qayy.po.Standard;
import cn.qayy.service.IBidService;
import cn.qayy.service.IPlanService;
import cn.qayy.service.IPolicyService;
import cn.qayy.service.IStandardService;
import cn.qayy.service.Uploadable;
import cn.qayy.utils.ArithUtil;
import cn.qayy.utils.DateUtils;
import cn.qayy.utils.DownLoadUtil;
import cn.qayy.utils.ExcelUtils;
import cn.qayy.utils.InitPlansUtil;
import cn.qayy.utils.JsonUtil;
import cn.qayy.utils.ResonseUtils;
import cn.qayy.utils.ServletContextUtils;
import cn.qayy.utils.StringUtil;
import cn.qayy.utils.UploadHandler;

/**
 * @author wangyu 协议表
 */
@Controller
@RequestMapping(value = "/policy/")
@SuppressWarnings("all")
public class PolicyController {
	Logger log = Logger.getLogger(PolicyController.class);
	// 注入service
	@Resource(name = "policyServiceImpl")
	private IPolicyService policyService = null;

	@Resource(name = "bidServiceImpl")
	private IBidService iBidService = null;

	@Resource(name = "standardServiceImpl")
	private IStandardService iStandardService = null;
	
	@Resource(name = "planServiceImpl")
	private IPlanService planService = null;

	List<String> multiselectCondi = new ArrayList<String>(); // 可多选的条件

	/***
	 * 批量导入
	 * @param file
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "upload")
	public Object upload(@RequestParam("excelFile") MultipartFile file, HttpServletRequest request) {
		Msg msg = null;
		int listSize = 0; // excel记录数
		try {
			Map<String, List<Uploadable>> map = UploadHandler.getLastData(file, PolicyDTO.class);
			
			if (map.get("fail") != null && !map.get("fail").isEmpty()) {// 前台提示消息
				// 验证不通过，前台提示消息
				List<Uploadable> list = map.get("fail");
				msg = new Msg(Constant.CHECK_CODE, list);
			} else {// DB持久化
				policyService.persistence(map,request,null);
				// 正常操作前台提示消息
				/**用户上传的总记录数**/
				if(map.get("totalCount") != null) {
					MsgInfo msgInfo = (MsgInfo)map.get("totalCount").get(0);
					listSize = StringUtil.parseInt(msgInfo.getErr_num());
				}
				msg = new Msg(Constant.SUCESSFUL_CODE, "总记录数：" + listSize + "，总成功数：" + listSize + "，请核查！");
			}
		} catch (Exception e) {
			//e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}
	/***
	 * 费用管理，查询协议相关数据自动填充
	 * @param startTime 页面比填写项
	 * @param endTime 页面比填写项
	 * @param customer 页面比填写项
	 * @param terminal 页面比填写项
	 * @param regulation 页面比填写项
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "selectPolicy")
	public Object selectPolicy(String customer,String terminal,String regulation,String startTime,String endTime) {
		Msg msg = null;
		try {
			Map<String,Object> params = new HashMap<String,Object>();
			ArrayList<String> products = new ArrayList<String>();
			ArrayList<String> packs = new ArrayList<String>();
			ArrayList<String> cnames = new ArrayList<String>();
			ArrayList<Integer> status = new ArrayList<Integer>();
			//客户
			if(StringUtil.isNotBlank(customer)) {
				params.put("client", customer);
			}
			//品种、包装
			if(StringUtil.isNotBlank(regulation)) {
				String product = regulation.substring(0, 1);
				String pack = regulation.substring(1);
				products.add(product);
				packs.add(pack);
				params.put("product", products);
				params.put("pack", packs);
			}
			//入货乙方 
			if(StringUtil.isNotBlank(terminal)) {
				params.put("qsterminal", terminal);
			}
			Policy policy = null;
			if(StringUtil.isNotBlank(customer)&&StringUtil.isNotBlank(terminal)) {
				List<Policy> list = policyService.selectByMap(params);
				if(list!=null && list.size()>0) {
					for (Policy p : list) {
						if(DateUtils.isDateGt2Eq(startTime,p.getXieyistarttime())
								&&DateUtils.isDateGt2Eq(p.getXieyiendtime(),endTime)) {
							policy = p;
							break;
						}
					}
				}
				if(policy == null) {
					msg = new Msg(Constant.FAIL_CODE,"没有找到相关记录，请先填写客户、终端品规信息。若已填写后仍没有找到，请手动完善。");
				} else {
					msg = new Msg(Constant.SUCESSFUL_CODE,policy);
				}
			} else {
				msg = new Msg(Constant.FAIL_CODE,"没有找到相关记录，请先填写客户、终端品规信息。若已填写后仍没有找到，请手动完善。");
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}
	
	@ResponseBody
	@RequestMapping(value = "selectPolicyList")
	public String selectPolicyList(@RequestParam Map<String, Object> condiMap,HttpServletRequest request,ModelMap model) {
		//对map进行过滤，除去空格
		condiMap = StringUtil.trim4Map(condiMap);
		
		String resultList = "";
		Msg msg = null;
		try {
			multiselectCondi.add("product");
			multiselectCondi.add("judge");
			multiselectCondi.add("pack");
			multiselectCondi.add("mode");
			multiselectCondi.add("xieyizhuangtai");
			multiselectCondi.add("terminaltype");
			multiselectCondi.add("kaipiaofangshi");
			multiselectCondi.add("jsmode");
			multiselectCondi.add("province");
			multiselectCondi.add("year");
			multiselectCondi.add("city");
			multiselectCondi.add("daqu");
			multiselectCondi.add("space");
			multiselectCondi.add("id");
			multiselectCondi.add("guihuanriqi");
			for (Object obj : condiMap.keySet()) {
				if (multiselectCondi.contains(obj)) {
					if (condiMap.get(obj).toString().startsWith("请选择")) {
						condiMap.put(obj.toString(), null);
					} else if (condiMap.get(obj) != null) {
						String str = (String) condiMap.get(obj).toString().trim();
						if (obj.equals("id")) {
							String[] array = StringUtil.strToArray(str, " ");
							if (array != null) {
								condiMap.put(obj.toString(), array);
							} else {
								condiMap.put(obj.toString(), null);
							}
						} else {
							String[] array = StringUtil.strToArray(str, ",");
							if (array != null) {
								condiMap.put(obj.toString(), array);
							} else {
								condiMap.put(obj.toString(), null);
							}
						}
					}
				} else if (condiMap.get(obj).equals("")) {
					condiMap.put(obj.toString(), null);
				}
			}
			PageInfo<Map<String, Object>> listMap = policyService.selectPolicyBy(condiMap);
			resultList = JSONObject.toJSONString(listMap);
			return resultList;
		} catch (Exception e) {
			// 异常后的前台提示消息
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
			resultList = JsonUtil.object2json(msg);
		}
		return resultList;
	}

	@ResponseBody
	@RequestMapping(value = "selectPolicyByID")
	public Object selectPolicyByID(@RequestParam Integer policyId) {
		Msg msg = null;
		try {
			Policy policy = policyService.selectPolicyByID(policyId);
			Object obj = JSONObject.toJSON(policy);
			return obj;
		} catch (Exception e) {
			//e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}
	

	/***
	 * 页面新增、修改协议
	 * 
	 * @param dto
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "changePolicy")
	public Object changePolicy(PolicyDTO dto, HttpServletRequest request) {
		Msg msg = null;
		String flag = (String) request.getParameter("flag");
		dto.setIsUpdate(flag);
		try {
			// 验证数据
			Map<String, List<Uploadable>> map = UploadHandler.getLastData(dto);
			if (map.get("fail") != null && !map.get("fail").isEmpty()) {
				/**
				 * 验证不通过，前台提示消息
				 */
				List<Uploadable> list = map.get("fail");
				msg = new Msg(Constant.CHECK_CODE, list);
			} else {// 验证通过，DB持久化
				policyService.persistence(map,request,null);
				msg = new Msg(Constant.SUCESSFUL_CODE, "总记录数：" + 1 + "，总成功数：" + 1 + "，请核查！");
			}
		} catch (Exception e) {
			//e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}
	
	/***
	 * 页面下载已筛选的记录
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "download")
	public void download(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<PolicyDTO> loadDataList = DownLoadUtil.getInstance().getTargetDownLoadDataList(PolicyDTO.class);
			String downloadPath = ExcelUtils.getInstance().dataToExcelDxls("协议表",StringUtil.listToStrArray(CollectionConstant.policy_mb),loadDataList);
			String url = request.getContextPath()+"/servlet/FileDownServlet?url="+downloadPath;
			response.sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
	/***
	 * 页面下载 重复的协议记录
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "download_re")
	public void download_re(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<PolicyDTO_RE> loadDataList = DownLoadUtil.getInstance().getTargetDownLoadDataList(PolicyDTO_RE.class);
			Set<PolicyDTO_RE> set = new HashSet<PolicyDTO_RE>();
			List<PolicyDTO_RE> listLast = new ArrayList<PolicyDTO_RE>();
			SimpleDateFormat SDF = new SimpleDateFormat("yyyy/MM/dd");
			
			for(PolicyDTO_RE re:loadDataList) {
				if(!set.contains(re)) {
					set.add(re);
				} else {
					Iterator<PolicyDTO_RE> iterator = set.iterator();
					while(iterator.hasNext()) {
						PolicyDTO_RE next = iterator.next();
						Date ds = SDF.parse(re.getXieyistarttime());
						Date de = SDF.parse(re.getXieyiendtime());
						Date d1 = SDF.parse(next.getXieyistarttime());
						Date d2 = SDF.parse(next.getXieyiendtime());
						boolean ok = false;
						if(re.getPage().equals(next.getPage())
								&&re.getProduct().equals(next.getProduct())
								&&re.getQsterminal().equals(next.getQsterminal())) {
							if(ds.getTime()==d1.getTime() && de.getTime()==d2.getTime()) {
								ok = true;
							}
							if(!ok) {
								if(ds.getTime()>d1.getTime() && ds.getTime()<d2.getTime()) {
									ok = true;
								}
							}
							if(!ok) {
								if(de.getTime()>d1.getTime() && de.getTime()<d2.getTime()) {
									ok = true;
								}
							}
							if(!ok) {
								if(d1.getTime()>ds.getTime() && d1.getTime()<de.getTime()) {
									ok = true;
								}
							}
							if(!ok) {
								if(d2.getTime()>ds.getTime() && d2.getTime()<de.getTime()) {
									ok = true;
								}
							}
							if(ok) {
								listLast.add(re);
								listLast.add(next);
								continue;
							}
						}
					}
				}
			}
			
			String downloadPath = ExcelUtils.getInstance().dataToExcelDxls("重复协议表",StringUtil.listToStrArray(CollectionConstant.policy_mb),listLast);
			String url = request.getContextPath()+"/servlet/FileDownServlet?url="+downloadPath;
			response.sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
	/***
	 * 页面下载已筛选的所有记录 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "downloadAll")
	public void downloadAll(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<PolicyAllDTO> loadDataList = DownLoadUtil.getInstance().getTargetDownLoadDataList(PolicyAllDTO.class);
			//csv方式
			//String filePath = ExcelUtils.exportCVS(loadDataList, StringUtil.listToArray(CollectionConstant.policys_notes));
			//String url = request.getContextPath()+"/servlet/FileDownServlet?url="+filePath;
			//xls方式
			String downloadPath = ExcelUtils.getInstance().dataToExcelDxls("协议表",StringUtil.listToStrArray(CollectionConstant.policys_notes),loadDataList);
			String url = request.getContextPath()+"/servlet/FileDownServlet?url="+downloadPath;
			
			response.sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
	
	/***
	 * 展示UI页面
	 * @return
	 */
	@RequestMapping(value="ui")
	public String ui() {
		return "policy_search";
	}
	
	/***
	 * 通过id更新协议状态，升级到5状态，降级到3状态
	 * @param QueryVO vo可以用来接收前台参数，前台的参数name必须和vo对象里的属性名保持一致。
	 * 前台需要的参数：id（可以允许空格隔开的多个id的字符串）,status（固定状态：3或5）
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="update")
	@ResponseBody
	public Object update(QueryVO vo,HttpServletRequest request) {
		Msg msg = null;
		try {
			//获取到协议id
			List<String> id2List = StringUtil.strId2List(vo.getId()," ");
			if(id2List != null && !id2List.isEmpty()) {
				Map<String, Object> params = new HashMap<String,Object>();
				params.put("ids", id2List);
				policyService.updateByParams(params,vo,request);
				//操作成功后显示消息
				msg = new Msg(Constant.SUCESSFUL_CODE, "总记录数：" + id2List.size() + "，总成功数：" + id2List.size() + "，请核查！");
			}
		} catch (Exception e) {
			//e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}
	
	/***
	 * 页面下载客户银行卡相关记录
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "downloadClientBank")
	public void downloadClientBank(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<ClientBankDTO> loadDataList = DownLoadUtil.getInstance().getTargetDownLoadDataList(ClientBankDTO.class);
			String downloadPath = ExcelUtils.getInstance().dataToExcelDxls("客户银行信息",StringUtil.listToStrArray(CollectionConstant.clientBank_mb),loadDataList);
			String url = request.getContextPath()+"/servlet/FileDownServlet?url="+downloadPath;
			response.sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
	/***
	 * 下载协议备案的完成率
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "downloadPolicyDemoWCL")
	public void downloadPolicyDemoWCL(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<PolicyDemoWCL> loadDataList = DownLoadUtil.getInstance().getTargetDownLoadDataList(PolicyDemoWCL.class);
			String downloadPath = ExcelUtils.getInstance().dataToExcelDxls("协议备案复核进度情况",StringUtil.listToStrArray(CollectionConstant.poilcy6_mb),loadDataList);
			String url = request.getContextPath()+"/servlet/FileDownServlet?url="+downloadPath;
			response.sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
	
	/***
	 * 获取待复制的id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "selectIds")
	public Object selectIds(HttpServletResponse response,HttpServletRequest request) {
		JSONObject json = new JSONObject();
		StringBuilder result=new StringBuilder();
		Msg msg = null;
		try {
			//获取缓存中的筛选条件
			Map<String, Object> params = (Map<String, Object>)DownLoadUtil.get("PolicyDTO");
			if(params == null) {
				params = new HashMap<String, Object>();
				params.put("t", "1127");
			}
			List<Integer> list = policyService.selectIdsByMap(params);
			if(list != null && list.size()>0) {
				for (Integer id : list) {
					result.append(id+" ");
				}
				result.deleteCharAt(result.toString().length()-1);
			}
		} catch(Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
			return msg;
		}
		json.put("ids", result.toString());
		ResonseUtils.writeResponseByJson(response, json);
		//封装成json返回给前台
		return null;
	}
}
